clear
clear all
cap log close

log using "log-files/2_Figure_D3.smcl", replace smcl

timer on 2

*------------*
* Figure D.3 *
*------------*
	* Figure D.3.a
	*-------------
		use "data/outputs/computo_verificadortrepdate_missingsatthend.dta", clear	
			
		* Creating a unique ordered ID for the problem precincts
		sort trep_missing_date pcs_so
		gen order = sum(trep_missing_date)
		replace order = 10000 + _n if order == 0

		* Creating a sorted tempfile of mshare and cshare just for problem precincts
		preserve
			keep if trep_missing_date == 1
			keep mshare_so cshare_so
			sort mshare_so
			rename mshare_so mshare_sorted
			rename cshare_so cshare_sorted
			gen order = _n
			tempfile sorted
			save `sorted'
		restore

		* Merging sorted mshare and cshare
		merge 1:1 order using `sorted'
		drop order _m

		sort pcs_so

		replace mshare_sorted = mshare_so if mshare_sorted == . & ///
			trep_missing_date == 0
		replace cshare_sorted = cshare_so if cshare_sorted == . & ///
			trep_missing_date == 0

		gen nulosshare = Nulos / total_so

		* Recinto ID
		egen reci_id = group(Pais Dep Prov Muni Loc Reci)
			   /* Note, in constructing the data set we made a correction
			   such that recinto names are unique within localities. */

		foreach var of varlist mshare_so cshare_so nulosshare {
			egen reci_mean = mean(`var'), by(reci_id)
			gen `var'_dm = `var' - reci_mean 
			drop reci_mean
			qui su `var'
			gen `var'_dm_plus = `var'_dm + `r(mean)' // Add overall mean for scale
		}

		lprobust nulosshare pcs_so, genvars
			
		twoway (line lprobust_gx_bc lprobust_eval, ///
					lcolor(gs6) lwidth(medthick)) ///
			(line lprobust_CI_l_rb lprobust_eval, ///
				lcolor(gs6) lwidth(thin) lpattern(dash)) ///
			(line lprobust_CI_r_rb lprobust_eval, ///
				lcolor(gs6) lwidth(thin) lpattern(dash)), ///
			graphregion(color(white)) ///
			ylab(, angle(0)) ///
			xlab() ///
			ytitle("Percent Null Ballots") ///
			xtitle("Proportion of Preliminary Vote Counted") ///
			xsize(7) ysize(5.55) ///
			legend(off)
		graph export "outputs/generated/Figure_D3a.pdf", replace

	* Figure D.3.b
	*-------------
		drop lprobust*
		lprobust nulosshare_dm pcs_so, genvars

		twoway (line lprobust_gx_bc lprobust_eval, ///
					lcolor(gs6) lwidth(medthick)) ///
			(line lprobust_CI_l_rb lprobust_eval, ///
				lcolor(gs6) lwidth(thin) lpattern(dash)) ///
			(line lprobust_CI_r_rb lprobust_eval, ///
				lcolor(gs6) lwidth(thin) lpattern(dash)), ///	   	
			graphregion(color(white)) ///
			ylab(,angle(0)) ///
			xlab() ///
			ytitle("Percent Null Ballots (De-Meaned by Precinct)") ///
			xtitle("Proportion of Preliminary Vote Counted") ///
			xsize(7) ysize(5.55) ///
			legend(off)
		graph export "outputs/generated/Figure_D3b.pdf", replace

*------------------------------------------------------------------------------*
timer off 2
timer list 2

log close
clear all
